package network;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class UdpEchoServer2 {
    private DatagramSocket socket = null;
    UdpEchoServer2(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动");
        while(true){
            //建立一个数据报用来接收客户端的数据
            DatagramPacket receivePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(receivePacket);
            //读取接收的数据
            String receive = new String(receivePacket.getData(), 0, receivePacket.getLength());
            String res = process(receive);
            DatagramPacket responsePacket = new DatagramPacket(res.getBytes(), res.getBytes().length, receivePacket.getSocketAddress());
            socket.send(responsePacket);
            System.out.printf("[%s:%d] req=%s, resp=%s\n",
                    receivePacket.getAddress().toString(), responsePacket.getPort(), receive, res);

        }
    }
    private String process(String s) {
        return s;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer2 server2 = new UdpEchoServer2(520);
        server2.start();
    }
}
